package com.estar.integaration.Controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.estar.integaration.Mapper.ProductionScheduleMapper;
import com.estar.integaration.Service.IProductionScheduleService;
import com.estar.integaration.Util.Util;
import com.estar.integaration.entity.ProductionSchedule;
import com.estar.integaration.entity.NoSQL.Res;
import com.google.gson.Gson;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@Api(value = "ProductionSchContrller",description = "排期表接口")
@RequestMapping("/production")
@RestController
public class ProductionScheduleController {

    @Autowired
    ProductionScheduleMapper productionScheduleMapper;
    @Autowired
    IProductionScheduleService iProductionScheduleService;

    Logger logger = LoggerFactory.getLogger(ProductionScheduleController.class);
    List<ProductionSchedule> scheduleList = new ArrayList<>();
    HashMap<String,ProductionSchedule> scheduleHashMap = new HashMap<>();

    /**
     * 获取所有在库的A码和来料日期
     * @return
     *
     */
    @GetMapping("/schetable")
    public Res getProductionSchedule(){
        scheduleList = iProductionScheduleService.selectAllPs();
        for(ProductionSchedule p: scheduleList){
            scheduleHashMap.put(p.getACode(),p);
        }
        String sLStr = new Gson().toJson(scheduleList);
        return new Res("20000",sLStr);
    }

    /**
     * 功能：将生产部的A码和标准来料日期进行提交
     * @param jsonObject
     * @return
     */
    @PostMapping("/insertSche")
    public Res insertProductionSchedule(@RequestBody JSONObject jsonObject){
        //取出所有的A码写入Hash
        if(scheduleList.size() == 0){
            scheduleList = productionScheduleMapper.selectList(null);
            for(ProductionSchedule p: scheduleList){
                scheduleHashMap.put(p.getACode(),p);
            }
        }
        JSONArray jsonArray = jsonObject.getJSONArray("equips");

        for(int i =0; i <jsonArray.size() ;i++){

            JSONObject tempJson = jsonArray.getJSONObject(i);
            //查询到purchaseList中的内容并且返回
            ProductionSchedule productionSchedule = new ProductionSchedule();

            productionSchedule.setACode((String) tempJson.get("aCode"));

            productionSchedule.setStandardComeTime(tempJson.getDate("standardComeTime"));

            if(productionSchedule.getACode().equals("") || productionSchedule.getACode() == null){
                return new Res("40000","存在空值");
            }
            if(scheduleHashMap.containsKey(productionSchedule.getACode())){
                return new Res("40000",productionSchedule.getACode());
            }
            //判断提交上来的A码是否有特殊字符,不判断长度或者aaaaa这种情况
            if(Util.isSpecialChar(productionSchedule.getACode()) == true){
                return new Res("40000","编号存在异常字符或");
            }
        }

        for(int j =0; j <jsonArray.size() ;j++){
            JSONObject tempJson = jsonArray.getJSONObject(j);
            ProductionSchedule productionSchedule = JSON.toJavaObject(tempJson,ProductionSchedule.class);
            productionSchedule.setACode(tempJson.getString("aCode"));
            productionSchedule.setStandardComeTime(tempJson.getDate("standardComeTime"));
            String id = UUID.randomUUID().toString().toUpperCase().replace("-","");
            productionSchedule.setId(id);
            scheduleHashMap.put(productionSchedule.getACode(),productionSchedule);//加入hash
            //写入数据库
            productionScheduleMapper.insert(productionSchedule);
        }
        scheduleList = productionScheduleMapper.selectList(null);
//        FormsHandler.setProducHaveNew(true);
        return new Res("20000",new Gson().toJson(scheduleList)); //重新查一遍返回
    }

    /**
     * 功能：删除排期记录
     * 流程： ① 先根据id删除对应的排期记录
     *       ② 再从数据库中select出表
     *       ③ 排序
     * @param id  排期记录的id
     * @Author HLF
     */
    @ApiOperation(value = "deleteSchedule",tags = "根据id删除排期记录",response = ProductionSchedule.class)
    @ApiResponses(value = {
            @ApiResponse(code = 20000,message = "success"),
            @ApiResponse(code = 40000,message = "fail")
    })
    @GetMapping("/deleteSchedule")
    public Res deleteSchedule(@RequestParam String id,@RequestParam String ACode){
        //根据id删除排期记录
        iProductionScheduleService.deleteProductionScheduleById(id);
        logger.info("deleteSchedule 删除成功");
        List<ProductionSchedule> psList = iProductionScheduleService.selectAllPs();
        scheduleHashMap.remove(ACode);
        List<ProductionSchedule> sortedpsList = psList.stream()
                .sorted(Comparator
                        .comparing(ProductionSchedule::getStandardComeTime)
                        .reversed())
                .collect(Collectors
                        .toList());
        return new Res("20000",new Gson().toJson(sortedpsList));
    }

}

